package com.zrx.app.android.fragment.calculators;

import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.udojava.evalex.Expression;
import com.zrx.app.android.R;


import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/*用于在CalculatorActivity类里面显示右边计算结果显示栏*/
public class Cal2Frag extends CalBase {

    private static final String TAG = "Cal2Frag";

    public static Cal2Frag newInstance(int rid) {
        Cal2Frag fragment = new Cal2Frag();
        Bundle bundle = new Bundle();                                   //Bundle携带数据，类似于Map
        bundle.putInt("rid",rid);
        fragment.setArguments(bundle);
        return fragment;
    }

    Map<String,Map> rootMap=new HashMap<>();

    int rid=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            rid = getArguments().getInt("rid");
        }

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_cal2, container, false);
        MyTextWatcher myTextWatcher=new MyTextWatcher();
        GridLayout grid= (GridLayout) view.findViewById(R.id.GRID_VIEW);

        try{
            JSONObject json=getTemplate(rid);
            String title=json.getString("title");
            JSONObject product=json.getJSONObject("product");
            int numOfProducts = product.size();
            grid.setColumnCount(numOfProducts+1);
            TextView titleText = new TextView(getContext());
            titleText.setText(title);
            grid.addView(titleText);
            Iterator<Map.Entry<String, Object>> iter = product.entrySet().iterator();
            String firstProductKey=null;
            for(int col=0;iter.hasNext();++col){
                Map.Entry<String, Object> prod = iter.next();
                TextView prodText = new TextView(getContext());
                prodText.setText(prod.getKey());
                prodText.setLayoutParams(new GridLayout.LayoutParams(
                        GridLayout.spec(0, GridLayout.CENTER),
                        GridLayout.spec(col+1, GridLayout.CENTER)));
                grid.addView(prodText);

                if(col==0){
                    firstProductKey=prod.getKey();
                }

                JSONObject inner = (JSONObject) prod.getValue();
                Iterator<Map.Entry<String, Object>> _iter = inner.entrySet().iterator();
                Map<String,Object> productMap=new HashMap<>();
                rootMap.put(prod.getKey(),productMap);
                for(int row=0;_iter.hasNext();++row){
                    Map.Entry<String, Object> item = _iter.next();
                    String itemKey = item.getKey();
                    JSONObject itemVal = (JSONObject)item.getValue();
                    if(col==0){
                        TextView itemTitle = new TextView(getContext());
                        itemTitle.setText(itemVal.getString("title")+":");
                        itemTitle.setLayoutParams(new GridLayout.LayoutParams(
                                GridLayout.spec(row+1, GridLayout.CENTER),
                                GridLayout.spec(0, GridLayout.RIGHT)));
                        grid.addView(itemTitle);
                    }

                    String type=itemVal.getString("type");
                    View itemView=null;
                    if(type.equals("out")){
                        TextView itemText = new TextView(getContext());
                        itemText.setText("");
                        itemText.setBackgroundColor(Color.GRAY);
                        itemText.setLayoutParams(new GridLayout.LayoutParams(
                                GridLayout.spec(row+1, GridLayout.CENTER),
                                GridLayout.spec(col+1, GridLayout.CENTER)));
                        itemText.setMinimumWidth(500);
                        productMap.put(item.getKey(),new Object[]{"out",itemVal.getString("exp"),itemText,itemVal.getString("format")});
                        itemView=itemText;
                    }else if(type.equals("coef")){
                        TextView itemText = new TextView(getContext());
                        itemText.setText(itemVal.getString("val"));
                        itemText.setBackgroundColor(Color.YELLOW);
                        itemText.setLayoutParams(new GridLayout.LayoutParams(
                                GridLayout.spec(row+1, GridLayout.CENTER),
                                GridLayout.spec(col+1, GridLayout.CENTER)));
                        itemText.setMinimumWidth(500);
                        productMap.put(item.getKey(),new Object[]{"coef",itemText});
                        itemView=itemText;
                    }else if(type.equals("in")){
                        if(col==0) {
                            EditText itemText = new EditText(getContext());
                            itemText.setText("");
                            itemText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
                            param.rowSpec = GridLayout.spec(row + 1, 1);
                            param.columnSpec = GridLayout.spec(col + 1, numOfProducts);
                            itemText.setLayoutParams(param);
                            itemText.setMinimumWidth(1100);
                            itemText.addTextChangedListener(myTextWatcher);
                            productMap.put(item.getKey(),new Object[]{"in",itemText});
                            itemView=itemText;
                        }else{
                            Object re = rootMap.get(firstProductKey).get(item.getKey());
                            productMap.put(item.getKey(),re);
                        }

                    }

                    if(itemView!=null) {
                        itemView.setMinimumHeight(40);
                        grid.addView(itemView);
                    }

                }
            }
        }catch (Exception e){
            Log.d(TAG,e.getMessage());
        }

        return view;
    }



    void calculate(){
        try{
            Iterator<Map.Entry<String, Map>> prodIter = rootMap.entrySet().iterator();
            while(prodIter.hasNext()){
                HashMap<String,String> map=new HashMap<>();
                Map.Entry<String, Map> prod = prodIter.next();
                Iterator itemIter = prod.getValue().entrySet().iterator();
                while(itemIter.hasNext()){
                    Map.Entry item = (Map.Entry) itemIter.next();
                    String itemKey= (String) item.getKey();
                    Object[] itemVal=(Object[])item.getValue();
                    if(itemVal[0].equals("in")){
                        EditText tv= (EditText) itemVal[1];
//                        double var=0;
//                        try{
//                            var=Double.valueOf(tv.getText().toString());
//                        }catch (Exception e){}
                        map.put(itemKey,tv.getText().toString());
                    }else if(itemVal[0].equals("out")){
                        map.put(itemKey, (String) itemVal[1]);
                    }else if(itemVal[0].equals("coef")){
                        TextView tv= (TextView) itemVal[1];
//                        double var=0;
//                        try{
//                            var=Double.valueOf(tv.getText().toString());
//
//                        }catch (Exception e){}
                        map.put(itemKey,tv.getText().toString());
                    }
                }

                itemIter = prod.getValue().entrySet().iterator();
                while(itemIter.hasNext()){
                    Map.Entry item = (Map.Entry) itemIter.next();
                    String itemKey= (String) item.getKey();
                    Object[] itemVal=(Object[])item.getValue();
                    if(itemVal[0].equals("out")){
                        String expStr = (String) itemVal[1];
                        TextView tv= (TextView) itemVal[2];

                        Expression exp = new Expression(expStr);
                        Iterator<String> keyIter = map.keySet().iterator();
                        while(keyIter.hasNext()){
                            String key = keyIter.next();
                            String var=map.get(key);
                            if(var==null || var.equals("")){
                                var="0";
                            }
                            exp.setVariable(key,var);
                        }
                        String format= (String) itemVal[3];
                        if(format!=null&&format.equals("none"))
                            tv.setText(exp.eval().toString());
                        else
                            tv.setText(nf.format(exp.eval()));

                    }
                }

            }

        }catch (Exception e){
            Log.d(TAG,e.getMessage());
        }

    }

}
